from django.shortcuts import render,HttpResponse,redirect
from app_test02 import models

def department(request):
    list=models.Department.objects.all()
    return  render(request,'department.html',{"list":list})

def department_add(request):
    if request.method=='GET':
        return  render(request,'departmentadd.html')
    else :
        # request.method=='POST':
        title=request.POST.get("title")
        models.Department.objects.create(title=title)
        return redirect('/department')

def department_delete(request):
    """删除部门"""
    id=request.GET.get('id')
    models.Department.objects.filter(id=id).delete()
    return redirect('/department')

def department_edit(request,id):
    """ 修改部门"""
    data=models.Department.objects.filter(id=id).first() # 符合条件的第一个 。要加 first() 不然报错
    if request.method=='GET':
        return render(request,'departmentedit.html',{'title':data.title})
    # print(data.title)
    title=request.POST.get('title')
    models.Department.objects.filter(id=id).update(title=title)
    return redirect('/department')

def user(request):
    list=models.Userinfo.objects.all()
    # print(list)
    # for  item in list:
        # item.get_gender_display()  根据gender_choices去得到对应的名称；django封装好的函数 ：get_名称_display()
        #item.depart.title 因为 depart  =  models.ForeignKey(to='Department',to_field='id',on_delete=models.CASCADE)设置了外键 直接可以获取到depart_id
        #strftime("%Y-%M-%D" 时间格式转换成字符串 ，DateTimeField 与 DateField格式不一样
        # print(item.name,item.get_gender_display(),item.depart.title,item.creat_time.strftime("%Y-%M-%D"))
    return render(request,'user.html',{'list':list})

def user_add(request):
    if request.method=='GET':
        content={
            'gender_choice':models.Userinfo.gender_choices,
            'department':models.Department.objects.all()
        }
        # print(content['content'][0][1])
        # test=(
        #     (1,"男"),
        #     (0,"女"),
        # )
        # for item in test:
        #     print(item[0])
        return render(request,'user_add.html',content)

    else:
        name=request.POST.get('user')
        age=request.POST.get('age')
        gender=request.POST.get('gender')
        salary=request.POST.get('salary')
        dep=request.POST.get('dep')
        creat_time=request.POST.get('creat_time')
        models.Userinfo.objects.create(name=name,age=age,gender=gender,salary=salary,depart_id=dep,creat_time=creat_time)
        return redirect('/user')

from django import forms
###### Form  ##############
# class MyForm(forms.Form):
#     name=forms.CharField(label='name')# widget=forms.input ,input插件
#     pwd=forms.CharField(label="密码",widget=forms.PasswordInput())

def user_add_form(request):
    form=MyForm()
    return render(request,'user_add_form.html',{'form':form})

# ModelForm
class MyModelForm(forms.ModelForm):
    # 为什么加了name后 'class':"form-control"就失效了？
    # name=forms.CharField(min_length=6,label='姓名') #如果要对填入字段加限制 在这里加

    class Meta:
        model=models.Userinfo
        fields=['name','age','gender','salary','depart','creat_time']
        # 这里就有点繁琐了，需要逐一添加class样式
        widgets={
            'name':forms.TextInput(attrs={'class':"form-control"}),
            'age':forms.TextInput(attrs={'class':"form-control"}),
            'gender':forms.Select(attrs={'class':"form-control"}),
            'salary':forms.TextInput(attrs={'class':"form-control"}),
            'depart':forms.Select(attrs={'class':"form-control"}),
            'creat_time':forms.DateInput(attrs={'class':"form-control"}),
        }

def user_add_modeldorm(request):
    if request.method=='GET':
        form=MyModelForm()
        return render(request,'user_add_form.html',{'form':form})
    #post数据进行校验
    else:
        form=MyModelForm(data=request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            # 如果数据正确 ，放进数据库。利用model form
            form.save()
            return  redirect('/user')
        else:
            print(form.errors)
            # 在html中 返回form.errors
            return render(request,'user_add_form.html',{'form':form})

def user_edit(request,id):
    row_data=models.Userinfo.objects.filter(id=id).first()
    if request.method=='GET':
        # modelform很强大，获取到一行的数据后，可以传入instance
        form=MyModelForm(instance=row_data)
        return render(request,'user_edit.html',{'form':form})
    else:
        # 注意！ 这里instance=row_data要加上
        form=MyModelForm(data=request.POST,instance=row_data)
        if form.is_valid():
            #保存的是用户输入的值，如果想选择固定字段保存：
            # form.instance.字段=值
            form.save()
            return  redirect('/user')
        else:
            return  render(request,'user_edit.html',{'form':form})

def user_delete(request,id):
    models.Userinfo.objects.filter(id=id).delete()
    return redirect('/user')

# from app_test02.utils import pagination
# def telnumber(request):
#     dict={}
#     value=request.GET.get('tel')
#     if value:
#         dict['number__contains']=value
#
#     queryset=models.TelNumber.objects.filter(**dict)
#     page_obj=pagination(request,queryset)
#     page_queryset=page_obj.page_queryset
#
#     dic_pagejoin=page_obj.html()
#     content={
#         'queryset':page_queryset,
#         'value':value,
#         'dic_pagejoin':dic_pagejoin
#     }
#     return render(request,'telnumber.html',content)

from django.utils.safestring import mark_safe
def telnumber(request):
    dict={}
    value=request.GET.get('tel')
    if value:
        dict['number__contains']=value

    #分页
    page=int(request.GET.get('page',1))#1为默认值
    pagesize=10 # 页面条数
    start=(page-1)*pagesize
    end=(page)*pagesize

    queryset=models.TelNumber.objects.filter(**dict)[start:end]
    # 总数据条数
    page_count=models.TelNumber.objects.filter(**dict).count()

    div_page,div=divmod(page_count,pagesize)
    if div:
        # 总页码数
        div_page+=1
    n=5
    start_page=page-n
    end_page=page+n+1
    #页码
    dic_page=[]
    pre='<li><a href="?page={}">上一页</a></li>'.format(page-1)
    dic_page.append(pre)
    # <li><a href="#">1</a></li>
    # for i in range(1,div_page+1): # 左闭右开，所以要＋1
    for i in range(start_page,end_page):
        if i==page:
            # str.format()
            fy='<li class="active"><a href="?page={}">{}</a></li>'.format(i,i)
        else:
            fy='<li><a href="?page={}">{}</a></li>'.format(i,i)
        dic_page.append(fy)
        #mark_safe 包裹html标签  表示安全  才能够在前端显示
    nextpage='<li><a href="?page={}">下一页</a></li>'.format(page+1)
    dic_page.append(nextpage)
    dic_pagejoin=mark_safe(''.join(dic_page))
    return render(request,'telnumber.html',{'queryset':queryset,'value':value,'dic_pagejoin':dic_pagejoin})


from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
class TelNumberForm(forms.ModelForm):
    # 验证方式一：
    # number=forms.CharField(
    #     label='电话号码',
    #     # validators数据校验
    #     # r'^1[3-9]\d{9}$'
    #     validators=[RegexValidator(r'^1\d{10}$','1开头的11位数字')],
    #     widget=forms.TextInput(attrs={'class':"form-control"})
    # )

    class Meta:
        model=models.TelNumber
        # fields='__all__' #所有字段
        # exclude=['$$$']# 排除某个字段
        fields=['number','price','level','status']
        widgets={
            'number':forms.TextInput(attrs={'class':"form-control"}),
            'price':forms.TextInput(attrs={'class':"form-control"}),
            'level':forms.Select(attrs={'class':"form-control"}),
            'status':forms.Select(attrs={'class':"form-control"}),
        }

        # 验证方式二：钩子函数 clean_字段
    def clean_number(self):
        new_number=self.cleaned_data['number']
        # # 不通过
        # if len(new_number)!=11:
        #     raise ValidationError('钩子--格式错误')
        # # 通过
        # return new_number

        exists=models.TelNumber.objects.filter(number=new_number).exists()
        if exists:
            raise ValidationError('手机号存在')
        else:
             return new_number

# queryset=models.TelNumber.objects.filter(number='15600006666')
# object=models.TelNumber.objects.filter(number='15600006666').first()
# exists=models.TelNumber.objects.filter(number='15600006666').exists()

def telnumberadd(request):
    if request.method=='GET':
        form=TelNumberForm()
        return render(request,'telnumberadd.html',{'form':form})
    else :
        # 获取POST的值
        form=TelNumberForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('/telnumber')
        else :
            return render(request,'telnumberadd.html',{'form':form})

# 编辑界面的数据调整，比如： 电话号码设置成不能编辑
class TelEditNumberForm(forms.ModelForm):
    # number=forms.CharField(
    #     label='电话号码',
    #     disabled=True,# 不可改
    #     validators=[RegexValidator(r'^1\d{10}$','1开头的11位数字')],
    #     widget=forms.TextInput(attrs={'class':"form-control"})
    # )
    class Meta:
        model=models.TelNumber
        # fields='__all__' #所有字段
        # exclude=['$$$']# 排除某个字段
        fields=['number','price','level','status']
        widgets={
            'number':forms.TextInput(attrs={'class':"form-control"}),
            'price':forms.TextInput(attrs={'class':"form-control"}),
            'level':forms.Select(attrs={'class':"form-control"}),
            'status':forms.Select(attrs={'class':"form-control"}),
        }

        # 钩子函数----编辑界面时，更改的电话号码不能重复，先要排除编辑时的电话号码
    def clean_number(self):
        new_number=self.cleaned_data['number']
        # self.instance.pk   选择编辑的id
        print(self.instance.pk)
        # exclude(id=self.instance.pk) 排除该id
        exists=models.TelNumber.objects.exclude(id=self.instance.pk).filter(number=new_number).exists()
        if exists:
            raise ValidationError('手机号已存在')
        else:
            return new_number

def telnumberedit(request,id):
    row_obj=models.TelNumber.objects.filter(id=id).first()
    if request.method =='GET':
        form=TelEditNumberForm(instance=row_obj)
        return  render(request,'telnumberedit.html',{'form':form})
    else:
        form=TelEditNumberForm(data=request.POST,instance=row_obj)
        if form.is_valid():
            form.save()
            return redirect('/telnumber')
        else :
             return render(request,'telnumberedit.html',{'form':form})

def telnumberdelete(request,id):
    models.TelNumber.objects.filter(id=id).delete()
    return redirect('/telnumber')



def admin(request):
#验证是否登录
    req=request.session.get('info')
    if not req:
        return redirect('/user_login')


    dict={}
    val=request.GET.get('q')
    if val:
        dict['name__contains']=val
    queryset=models.Admin.objects.filter(**dict)

    return render(request,'admin.html',{'queryset':queryset,'val':val})

from app_test02.utils.encryption import md5

class AdminModelForm(forms.ModelForm):
    # 新的字段
    confirm_password=forms.CharField(label='确认密码',widget=forms.PasswordInput(attrs={'class':"form-control"}))

    class Meta():
        model=models.Admin
        fields=['name','password','confirm_password']

        # 样式
        widgets={
            'name':forms.TextInput(attrs={'class':"form-control"}),
            'password':forms.PasswordInput(attrs={'class':"form-control"}),
            # 'confirm_password':forms.PasswordInput(attrs={'class':"form-control"})
        }
    def clean_password(self):
        pwd=self.cleaned_data.get('password')
        # return md5(pwd)
        return pwd

    def clean_confirm_password(self):
        print(self.cleaned_data)

        # confirm=md5(self.cleaned_data.get('confirm_password'))
        confirm=(self.cleaned_data.get('confirm_password'))
        pwd=self.cleaned_data.get('password')

        print(confirm,pwd)
        if pwd != confirm:
            raise ValidationError('密码不相同')
        return confirm #return 返回的什么  数据库中就存什么。 这里不放也行



def admin_add(request):
    # modelform
    if request.method=='GET':
        form=AdminModelForm()
        return render(request,'admin_add.html',{'form':form})
    else:
        form=AdminModelForm(data=request.POST)
        if form.is_valid():
            form.save()
            return  redirect('/admin')
        else :
            return render(request,'admin_add.html',{'form':form})


class AdminEditModelForm(forms.ModelForm):
    class Meta():
        model=models.Admin
        fields=['name']
        # 样式
        widgets={
            'name':forms.TextInput(attrs={'class':"form-control"})
        }
"""
def department_edit(request,id):
    # 修改部门
    data=models.Department.objects.filter(id=id).first() # 符合条件的第一个 。要加 first() 不然报错
    if request.method=='GET':
        return render(request,'departmentedit.html',{'title':data.title})
    # print(data.title)
    title=request.POST.get('title')
    models.Department.objects.filter(id=id).update(title=title)
    return redirect('/department')
"""
def admin_edit(request,id):
    row_obj=models.Admin.objects.filter(id=id).first()

    # print(models.Admin.objects.filter(id=id).first(),flush=True)
    print(models.Admin.objects.filter(id=id))

    if request.method == 'GET':
        form=AdminEditModelForm(instance=row_obj)
        return  render(request,'admin_edit.html',{'form':form})
    else:
        form=AdminEditModelForm(data=request.POST,instance=row_obj)
        if form.is_valid():
            form.save()
            return redirect('/admin')
        else :
            return render(request,'admin_edit.html',{'form':form})

def admin_delete(request,id):
    models.Admin.objects.filter(id=id).delete()
    return redirect('/admin')


class LoginModelForm(forms.ModelForm):
    class Meta:
        model=models.Admin
        fields=['name','password']
        widgets={
            'name':forms.TextInput(attrs={'class':"form-control"}),
            'password':forms.PasswordInput(attrs={'class':"form-control"})
        }

    def clean_password(self):
        psw=self.cleaned_data.get('password')
        # return md5(psw) # 密码md5加密，一定要返回
        return  psw


def user_login(request):
    if request.method=='GET':
        form=LoginModelForm()
        return render(request,'user_login.html',{'form':form})
    else:
        form=LoginModelForm(data=request.POST)
        if form.is_valid():
            # form.save() # 这个把输入的值保存到数据库中 这里不需要保存。直接验证。
            print('password',form.cleaned_data) # 字典
            # 去数据库查找 是否有
            obj=models.Admin.objects.filter(**form.cleaned_data).first()
            if not obj:
                # 报错
                # form.add_error('name','账号或密码错误')
                form.add_error('password','账号或密码错误')
                return render(request,'user_login.html',{'form':form})
            # 网站生成随机字符串，写到浏览器cookie、网站session中。
            request.session['info'] ={'id':obj.id,'name':obj.name}
            # return HttpResponse('提交成功')
            return  redirect('/admin')
        else:
            return render(request,'user_login.html',{'form':form})
